package com.dk.bleNfc.DeviceManager;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

public class BluetoothConnectionManager {

    private static final String TAG = "BluetoothConnection";
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    private BluetoothAdapter bluetoothAdapter;
    private BluetoothDevice bluetoothDevice;     // 你的目标蓝牙设备
    private BluetoothSocket bluetoothSocket;
    private InputStream inputStream;
    private Thread listenThread;
    private ConnectedThread connectedThread;

    private final Handler uiHandler; // 用于更新UI（可选）

    public BluetoothConnectionManager(Handler handler) {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        this.uiHandler = handler;
    }

    // 设置目标设备（可通过 MAC 或 BluetoothDevice 对象）
    public void setTargetDevice(BluetoothDevice device) {
        this.bluetoothDevice = device;
    }

    // 开始连接
    public void connect() {
        if (bluetoothDevice == null) {
            Log.e(TAG, "BluetoothDevice is not set.");
            return;
        }

        new Thread(() -> {
            try {
                bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(MY_UUID);
                bluetoothAdapter.cancelDiscovery(); // 停止搜索，提高连接速度

                Log.d(TAG, "正在连接到蓝牙设备...");
                bluetoothSocket.connect(); // 阻塞式连接

                Log.d(TAG, "蓝牙连接成功！");

                // 获取输入流
                inputStream = bluetoothSocket.getInputStream();

                // 启动一个线程监听数据
                connectedThread = new ConnectedThread(inputStream);
                connectedThread.start();

            } catch (IOException e) {
                Log.e(TAG, "连接失败: " + e.getMessage());
                try {
                    if (bluetoothSocket != null) bluetoothSocket.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }).start();
    }

    // 断开连接
    public void disconnect() {
        try {
            if (connectedThread != null) {
                connectedThread.interrupt();
            }
            if (bluetoothSocket != null) {
                bluetoothSocket.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            Log.d(TAG, "蓝牙连接已关闭");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 内部类：负责从输入流读取数据
    private class ConnectedThread extends Thread {
        private final InputStream mmInStream;

        public ConnectedThread(InputStream inputStream) {
            this.mmInStream = inputStream;
        }

        @Override
        public void run() {
            byte[] buffer = new byte[1024]; // 缓冲区
            int bytes;

            while (!isInterrupted()) {
                try {
                    // 阻塞，直到有数据可读
                    if (mmInStream != null) {
                        bytes = mmInStream.read(buffer); // 读取到的字节数
                        if (bytes > 0) {
                            // 处理接收到的数据
                            byte[] receivedBytes = new byte[bytes];
                            System.arraycopy(buffer, 0, receivedBytes, 0, bytes);

                            // 在主线程中处理（可选，比如更新UI）
                            final byte[] finalBytes = receivedBytes;
                            if (uiHandler != null) {
                                uiHandler.post(() -> handleReceivedData(finalBytes));
                            } else {
                                // 或者直接在这里处理
                                handleReceivedData(finalBytes);
                            }
                        }
                    }
                } catch (IOException e) {
                    Log.e(TAG, "读取数据出错，连接可能已断开: " + e.getMessage());
                    break;
                }
            }
        }
    }

    // 处理接收到的数据（你可以根据协议解析按键）
    private void handleReceivedData(byte[] data) {
        // 示例：假设设备每次只发送一个字节，比如 0x01 表示按钮1
        for (byte b : data) {
            Log.d(TAG, "收到字节数据: 0x" + String.format("%02X", b));

            switch (b) {
                case 0x01:
                    Log.d(TAG, "🔘 按钮 1 被按下");
                    // 执行按钮1的逻辑
                    break;
                case 0x02:
                    Log.d(TAG, "🔘 按钮 2 被按下");
                    // 执行按钮2的逻辑
                    break;
                case 0x03:
                    Log.d(TAG, "🔘 按钮 3 被按下");
                    break;
                // 添加更多的按键映射
                default:
                    Log.d(TAG, "🔒 未知按键或数据: 0x" + String.format("%02X", b));
            }
        }

        // 如果设备发送的是字符串，比如 "BTN1"，可以这样解析：
                /*
        String received = new String(data, StandardCharsets.UTF_8);
        Log.d(TAG, "收到字符串: " + received);
        if (received.contains("BTN1")) { ... }
        */
    }
}
